package com.dyz.leetcode;

import java.util.Arrays;

public class BuildTree105 {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        //递归 preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] 前序遍历 第一个是根节点，中序遍历根节点在中间
        if(preorder==null||inorder==null||preorder.length==0||inorder.length==0){return null;}
        TreeNode root = new TreeNode(preorder[0]);
        int n = preorder.length;
        for(int i=0;i<n;i++){
            if(inorder[i]==root.val){
                root.left = buildTree(Arrays.copyOfRange(preorder,1,i+1), Arrays.copyOfRange(inorder,0,i));//注意开闭区间[0,i)
                root.right = buildTree(Arrays.copyOfRange(preorder,i+1, n),Arrays.copyOfRange(inorder,i+1,n));
            }
        }
        return root;
    }
}
